package com.example.ktapplication.fragment

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.*
import com.example.ktapplication.adapter.LeftNavigationAdapter
import com.example.ktapplication.adapter.RightNavigationAdapter
import com.example.ktapplication.bean.NavData
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.NavViewModel
import com.example.ktapplication.state.NavState
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import com.example.ktapplication.utils.jumpUrl
import com.example.ktapplication.view.CustomTitleBar
import com.example.ktapplication.view.StatusLayout
import com.example.ktapplication.view.TopItemDecoration
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class NavFragment : Fragment(), View.OnClickListener {
    companion object {
        private var instance: NavFragment? = null

        fun getInstance(): NavFragment {
            if (instance == null) {
                instance = NavFragment()
            }
            return instance!!
        }
    }

    private lateinit var titleBar: CustomTitleBar
    private lateinit var imgFind: ImageView
    private lateinit var imgMenu: ImageView
    private lateinit var txtTitle: TextView
    private lateinit var mRefresh: SmartRefreshLayout

    private lateinit var mStatusLayout: StatusLayout
    var mNavContainer: View? = null
    private lateinit var loadingView: View
    private lateinit var emptyView: View
    private lateinit var errorView: View
    private lateinit var netView: View

    private lateinit var rvLeft:RecyclerView
    private lateinit var rvRight:RecyclerView

    var leftList = mutableListOf<NavData>()
    private lateinit var navModel : NavViewModel
    private var navJob: Job? = null

    var type: StateLayoutMode? = null
    var isRefresh:Boolean=false

    //初始化左侧recyclerview的adapter
    private lateinit var leftNavigationAdapter: LeftNavigationAdapter

    //初始化右侧recyclerview的adapter
    private lateinit var rightNavigationAdapter: RightNavigationAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // 返回你的布局或视图
        return inflater.inflate(R.layout.fragment_mine, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navModel = ViewModelProvider(this)[NavViewModel::class.java]
        navModel.getNav()
        ///初始化组件
        initView(view)
        waitData()
    }

    /**
     * 左右两个RecyclerView联动
     */
    private fun recyclerViewLinkage() {
        val manager = rvRight.layoutManager as LinearLayoutManager
        //左边联动右边
        leftNavigationAdapter.setOnItemClickListener(
            LeftNavigationAdapter.OnItemClickListener { position: Int ->
            if (position!=0){
                mRefresh.setEnableRefresh(false)
            }else{
                mRefresh.setEnableRefresh(true)
            }
            leftNavigationAdapter.setChoose(position)
            manager.scrollToPositionWithOffset(position, 0)
        })
        //右边联动左边
        rvRight.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val firstItemPosition = manager.findFirstVisibleItemPosition()
                if (firstItemPosition != -1) {
                    rvLeft.smoothScrollToPosition(firstItemPosition)
                    leftNavigationAdapter.setChoose(firstItemPosition)
                }
            }
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //newState分 0,1,2三个状态,2是滚动状态,0是停止
                super.onScrollStateChanged(recyclerView, newState)
                //-1代表顶部,返回true表示没到顶,还可以滑
                //1代表底部,返回true表示没到底部,还可以滑
                val bottom = recyclerView.canScrollVertically(1)
                val top = recyclerView.canScrollVertically(-1)
                if (!top){
                    mRefresh.setEnableRefresh(true)
                }else{
                    mRefresh.setEnableRefresh(false)
                }
            }
        })
    }

    fun initView(view: View){
        mRefresh = view.findViewById(R.id.smartRefreshLayout)
        mRefresh.setEnableLoadMore(false)
        titleBar=view.findViewById<CustomTitleBar>(R.id.titleBar)
        imgFind=titleBar.findViewById<ImageView>(R.id.img_find)
        imgMenu=titleBar.findViewById<ImageView>(R.id.img_menu)
        txtTitle=titleBar.findViewById<TextView>(R.id.txt_title)
        txtTitle.text="导航"
        initStatusLayou(view)
        initNavContainer()
        initEvent()
    }

    fun initNavContainer() {
        mNavContainer = layoutInflater.inflate(R.layout.fragment_nav_container, null)
        rvLeft=mNavContainer!!.findViewById<RecyclerView>(R.id.rvLeft)
        rvRight=mNavContainer!!.findViewById<RecyclerView>(R.id.rvRight)
        leftNavigationAdapter = LeftNavigationAdapter(context as Activity )
        rvLeft.adapter = leftNavigationAdapter
        rightNavigationAdapter = RightNavigationAdapter(context as Activity)
        rightNavigationAdapter.navItemClickAction={
            requireActivity().jumpUrl(it.link,it.title)
        }
        rvRight.adapter = rightNavigationAdapter
        recyclerViewLinkage()
    }

    private fun initStatusLayou(view: View) {
        mStatusLayout = view.findViewById<StatusLayout>(R.id.statusLayout)
        loadingView = layoutInflater.inflate(R.layout.status_layout_loading, null)
        mStatusLayout.setLoadingLayout(loadingView)
        emptyView = layoutInflater.inflate(R.layout.status_layout_empty, null)
        mStatusLayout.setEmptyLayout(emptyView)
        errorView = layoutInflater.inflate(R.layout.status_layout_error, null)
        mStatusLayout.setErrorLayout(errorView);
        netView = layoutInflater.inflate(R.layout.status_layout_net, null)
        mStatusLayout.setNetLayout(netView)
        emptyView.findViewById<LinearLayout>(R.id.btn_empty).setOnClickListener(this);
        errorView.findViewById<LinearLayout>(R.id.btn_error).setOnClickListener(this);
        mStatusLayout.setMode(StateLayoutMode.LOADING);
    }

    override fun onClick(view:View?) {
        TODO("Not yet implemented")
    }

    fun  waitData(){
        navJob=lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            navModel.state.collect{ state ->
                when(state){
                    is NavState.OnSuccess -> {
                        if (state.nav!=null){
                            if(state.nav!!.errorCode==0 ){
                                if (state.nav!!.data.isEmpty()){
                                    type = StateLayoutMode.EMPTY
                                    showErroeView(type!!)
                                }else{
                                    withContext(Dispatchers.Main){
                                        mRefresh.finishRefresh()
                                        leftList.clear()
                                        leftList.addAll(state.nav!!.data)
                                        leftList[0].chose=true
                                        leftNavigationAdapter.leftList.clear()
                                        leftNavigationAdapter.leftList.addAll(leftList)
                                        rightNavigationAdapter.rightList.clear()
                                        rightNavigationAdapter.rightList.addAll(state.nav!!.data)
                                        if (!isRefresh){
                                            val top = TopItemDecoration(context as Activity).apply {
                                                this.tagListener = {
                                                    leftList[it].name.toString()
                                                }
                                            }
                                            rvRight.addItemDecoration(top)
                                        }
                                        leftNavigationAdapter.notifyDataSetChanged()
                                        rightNavigationAdapter.notifyDataSetChanged()
                                        if (!isRefresh){
                                            mStatusLayout.addView(mNavContainer!!)
                                            mStatusLayout.setMode(StateLayoutMode.CONTENT)
                                        }
                                        isRefresh=false
                                    }
                                }
                            }else{
                                type = StateLayoutMode.ERROR
                                showErroeView(type!!)
                            }
                            state.nav!!.count+=1
                        }
                    }
                    is NavState.OnError -> {
                        val error = state.exception!!.message
                        type = StateLayoutMode.ERROR
                        showErroeView(type!!)
                    }
                }
            }
        }
    }

    fun initEvent(){
        imgFind.setOnClickListener(View.OnClickListener {
            EventBusUtil.eventBus.post(Event.MainClickFind())
        })
        imgMenu.setOnClickListener(View.OnClickListener {
            EventBusUtil.eventBus.post(Event.MainClickMenu())
        })
        //下拉刷新
        mRefresh.setOnRefreshListener(object : OnRefreshListener {

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isRefresh=true
                navModel.getNav()
                refreshLayout.finishRefresh()
            }
        })
    }

    private fun showErroeView(type: StateLayoutMode) {
        lifecycleScope.launch(Dispatchers.Main) {
            mRefresh.finishRefresh()
            mStatusLayout.setMode(type)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        navJob!!.cancel()
    }
}
